// 🎯 S6 终极策略执行器：融合 S1 + S2 + S3 + S4
const esm = require("esm")(module);
const path = require("path");
const _ = require("lodash");
const fs = require("fs");

// 项目模块
const { readAllValues } = esm("../../../awakened-potential/helpers/readAllValues.js");
const checkAccuracy = esm("../../utils/checkAccuracy.js");
const select32NumbersByS6 = require("./select32NumbersByS6.js");

// 读取历史开奖数据
const allValues = readAllValues("m");

// 所有号码（01 ~ 49）
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  (i + 1).toString().padStart(2, "0")
);

// ✅ 控制窗口
const windowSize = 39;
const useWindow = true;

// ✅ 初始化状态
const predictResults = [];
const numberWrongMap = {};
const transitionMatrix = {}; // S3 转移矩阵

allNumbers.forEach((num) => {
  numberWrongMap[num] = 0;
  transitionMatrix[num] = {};
  allNumbers.forEach((to) => {
    transitionMatrix[num][to] = 0;
  });
});

// ✅ 主循环
allValues.forEach((item, index) => {
  const temp = useWindow
    ? allValues.slice(Math.max(0, index - windowSize), index)
    : allValues.slice(0, index);

  if (temp.length === 0 || index === 0) return;

  const finalSelected = select32NumbersByS6(temp, transitionMatrix, numberWrongMap);

  const isHit = checkAccuracy(finalSelected, item.number);
  predictResults.push(isHit);

  // ✅ 更新转移矩阵（S3）
  const prev = allValues[index - 1].number;
  const curr = item.number;
  if (transitionMatrix[prev] && transitionMatrix[prev][curr] != null) {
    transitionMatrix[prev][curr]++;
  }

  // ✅ 更新每个号码的连错次数（S4）
  allNumbers.forEach((num) => {
    if (finalSelected.includes(num)) {
      if (item.number === num) {
        numberWrongMap[num] = 0;
      } else {
        numberWrongMap[num] += 1;
      }
    }
  });
});

// ✅ 统计
const total = predictResults.length;
const correct = predictResults.filter((x) => x === 1).length;
const accuracy = total > 0 ? ((correct / total) * 100).toFixed(2) : 0;

let maxWrongStreak = 0;
let currentStreak = 0;
predictResults.forEach((res) => {
  if (res === 0) {
    currentStreak++;
    maxWrongStreak = Math.max(maxWrongStreak, currentStreak);
  } else {
    currentStreak = 0;
  }
});

// ✅ 输出结果
console.log(`\u2728 使用 S6 策略（S1 + S2 + S3 投票 + S4 淘汰）`);
console.log(`预测总数: ${total}`);
console.log(`命中次数: ${correct}`);
console.log(`准确率: ${accuracy}%`);
console.log(`最大连续错误次数: ${maxWrongStreak}`);